package com.soft.base.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import javax.net.ssl.*;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Map;
/**
 * class
 *
 * @author user
 * @date 2020/06/05
 */
public class HttpUtil {

    static {
        try {
            TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }

                @Override
                public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {

                }

                @Override
                public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {

                }
            }
            };

            SSLContext sc = SSLContext.getInstance("TLSv1.2");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

            HostnameVerifier allHostsValid = new HostnameVerifier() {
                @Override
                public boolean verify(String requestedHost, SSLSession remoteServerSession) {
                    return requestedHost.equalsIgnoreCase(remoteServerSession.getPeerHost());
                }
            };
            HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
        } catch (NoSuchAlgorithmException e) {
        } catch (KeyManagementException e) {
        }
    }

    public static String get(String url, Map<String, String> header, Map<String, Object> param) {
        String result = "";
        BufferedReader in;
        OutputStream out;
        try {
            StringBuffer urlSb = new StringBuffer();
            urlSb.append(url).append("?");
            if (null != param) {
                for (String key : param.keySet()) {
                    urlSb.append(URLEncoder.encode(key, "utf-8"))
                            .append("=")
                            .append(URLEncoder.encode(param.get(key).toString(), "utf-8"))
                            .append("&");
                }
            }
            URL realUrl = new URL(urlSb.toString());
            HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
            if (null != header) {
                for (String key : header.keySet()) {
                    connection.setRequestProperty(key, header.get(key));
                }
            }
            connection.setDoOutput(true);
            connection.setDoInput(true);
            try {
                in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String line;
                while ((line = in.readLine()) != null) {
                    result += line;
                }
            } catch (Exception e) {
                throw new RuntimeException(e.getMessage(), e);
            }
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage(), e);
        }
        return result;
    }

    public static String get(String url, Map<String, Object> param) {
        return get(url, new HashMap<String, String>(128), param);
    }

    public static String get(String url) {
        return get(url, new HashMap<String, Object>(128));
    }

    public static String post(String url, Map<String, String> header, byte[] body) {

        String result = "";
        BufferedReader in;
        OutputStream out;
        try {
            URL realUrl = new URL(url);
            HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
            if (null != header) {
                for (String key : header.keySet()) {
                    connection.setRequestProperty(key, header.get(key));
                }
            }
            connection.setDoOutput(true);
            connection.setDoInput(true);
            try {
                out = connection.getOutputStream();
                out.write(body);
                out.flush();
            } catch (Exception e) {
                throw e;
            }
            try {
                in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String line;
                while ((line = in.readLine()) != null) {
                    result += line;
                }
            } catch (Exception e) {
                throw new RuntimeException(e.getMessage(), e);
            }
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage(), e);
        }
        return result;
    }

    public static String post(String url, Map<String, String> param) {
        StringBuffer urlSb = new StringBuffer();
        if (null != param) {
            for (String key : param.keySet()) {
                try {
                    urlSb.append(URLEncoder.encode(key, "utf-8"))
                            .append("=")
                            .append(URLEncoder.encode(param.get(key).toString(), "utf-8"))
                            .append("&");
                } catch (Exception e) {
                    throw new RuntimeException(e.getMessage(), e);
                }
            }
        }
        byte[] bytes = urlSb.toString().getBytes();
        return post(url, new HashMap<String, String>(128), bytes);
    }

    public static String post(String url, Map<String, String> header, String body) {
        return post(url, header, body.getBytes());
    }

    public static String post(String url) throws Exception {
        return post(url, new HashMap<String, String>(128));
    }

    public static String post(String url, String body) {
        return post(url, null, body.getBytes());
    }

}
